package com.example.backend.controller;

import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.dto.ApiResponse;
import com.example.backend.dto.CreateTicketRequest;
import com.example.backend.service.TicketCreationService;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

/**
 * 优化的工单控制器
 * 专门解决工单创建超时问题
 */
@Slf4j
@RestController
@RequestMapping("/api/tickets")
@Tag(name = "工单管理（优化版）", description = "优化的工单创建和管理功能")
@RequiredArgsConstructor
public class TicketOptimizedController {

    private final TicketCreationService ticketCreationService;

    /**
     * 快速创建工单 - 优化版本
     * 解决超时问题的主要接口
     */
    @PostMapping("/create-fast")
    @Operation(summary = "快速创建工单", description = "优化版本的工单创建，解决超时问题")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createTicketFast(
            @Valid @RequestBody CreateTicketRequest request,
            @AuthenticationPrincipal User currentUser) {
        
        log.info("🚀 接收到快速创建工单请求: {} (用户: {})", request.getTitle(), currentUser.getUsername());
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 使用优化的创建服务
            Ticket ticket = ticketCreationService.createTicketFast(request, currentUser);
            
            long duration = System.currentTimeMillis() - startTime;
            
            // 返回精简的响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("id", ticket.getId());
            response.put("ticketNumber", ticket.getTicketNumber());
            response.put("title", ticket.getTitle());
            response.put("status", ticket.getStatus());
            response.put("createdAt", ticket.getCreatedAt());
            response.put("responseTime", duration + "ms");
            
            log.info("✅ 工单创建成功响应: {} (总耗时: {}ms)", ticket.getTicketNumber(), duration);
            
            return ResponseEntity.ok(ApiResponse.success("工单创建成功", response));
            
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startTime;
            log.error("❌ 工单创建失败 (耗时: {}ms): {}", duration, e.getMessage(), e);
            
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("工单创建失败: " + e.getMessage()));
        }
    }

    /**
     * 工单创建性能测试接口
     */
    @PostMapping("/performance-test")
    @Operation(summary = "工单创建性能测试", description = "用于测试工单创建的性能表现")
    public ResponseEntity<ApiResponse<Map<String, Object>>> performanceTest(
            @RequestParam(defaultValue = "1") int count,
            @AuthenticationPrincipal User currentUser) {
        
        log.info("🧪 开始工单创建性能测试: {} 次", count);
        
        Map<String, Object> result = new HashMap<>();
        long totalStartTime = System.currentTimeMillis();
        
        try {
            java.util.List<Long> responseTimes = new java.util.ArrayList<>();
            
            for (int i = 0; i < count; i++) {
                long startTime = System.currentTimeMillis();
                
                CreateTicketRequest request = new CreateTicketRequest();
                request.setTitle("性能测试工单 #" + (i + 1));
                request.setDescription("这是第 " + (i + 1) + " 个性能测试工单");
                request.setPriority(com.example.backend.domain.enums.TicketPriority.LOW);
                request.setSource(com.example.backend.domain.enums.TicketSource.API);
                
                ticketCreationService.createTicketFast(request, currentUser);
                
                long duration = System.currentTimeMillis() - startTime;
                responseTimes.add(duration);
            }
            
            long totalDuration = System.currentTimeMillis() - totalStartTime;
            
            // 计算统计数据
            double avgTime = responseTimes.stream().mapToLong(Long::longValue).average().orElse(0.0);
            long minTime = responseTimes.stream().mapToLong(Long::longValue).min().orElse(0);
            long maxTime = responseTimes.stream().mapToLong(Long::longValue).max().orElse(0);
            
            result.put("total_requests", count);
            result.put("total_time_ms", totalDuration);
            result.put("avg_time_ms", Math.round(avgTime));
            result.put("min_time_ms", minTime);
            result.put("max_time_ms", maxTime);
            result.put("requests_per_second", Math.round((double) count / totalDuration * 1000));
            result.put("timestamp", Instant.now());
            
            log.info("✅ 性能测试完成: {} 次请求, 平均耗时: {}ms", count, Math.round(avgTime));
            
            return ResponseEntity.ok(ApiResponse.success("性能测试完成", result));
            
        } catch (Exception e) {
            long totalDuration = System.currentTimeMillis() - totalStartTime;
            log.error("❌ 性能测试失败 (耗时: {}ms): {}", totalDuration, e.getMessage(), e);
            
            result.put("error", e.getMessage());
            result.put("failed_after_ms", totalDuration);
            
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("性能测试失败"));
        }
    }

    /**
     * 获取创建性能统计
     */
    @GetMapping("/creation-stats")
    @Operation(summary = "获取工单创建统计", description = "查看工单创建的性能统计信息")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCreationStats() {
        
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 系统状态
            Runtime runtime = Runtime.getRuntime();
            stats.put("jvm_memory_used_mb", (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024);
            stats.put("jvm_memory_total_mb", runtime.totalMemory() / 1024 / 1024);
            stats.put("jvm_memory_max_mb", runtime.maxMemory() / 1024 / 1024);
            
            // 当前时间
            stats.put("server_time", Instant.now());
            stats.put("uptime_ms", System.currentTimeMillis());
            
            // 建议的优化配置
            Map<String, Object> recommendations = new HashMap<>();
            recommendations.put("database_timeout", "建议设置为30秒");
            recommendations.put("connection_pool", "建议最大连接数50");
            recommendations.put("jvm_heap", "建议最小2GB");
            stats.put("recommendations", recommendations);
            
            return ResponseEntity.ok(ApiResponse.success("统计信息获取成功", stats));
            
        } catch (Exception e) {
            log.error("❌ 获取创建统计失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }
}
